<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { addAddressApi, editAddressApi, getAddressByIdApi } from '../../services/address'
import type { address, addressParams } from '../../types/address'

const props = defineProps<{
  id?: string
}>()

uni.setNavigationBarTitle({ title: props.id ? '修改地址' : '新增地址' })

onLoad(() => {
  if (props.id) getAddress()
})

const getAddress = async () => {
  // 获取地址
  const res = await getAddressByIdApi(props.id!)
  form.value = res.result as addressParams & { fullLocation: string }
}

const formRef = ref<UniHelper.UniFormsInstance>(),
  rules: UniHelper.UniFormsRules = {
    receiver: { rules: [{ required: true, errorMessage: '请输入收货人姓名' }] },
    contact: {
      rules: [
        { required: true, errorMessage: '请输入收货人电话' },
        {
          pattern:
            /^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9]|17[0|1|2|3|5|6|7|8|9]|19[0|1|2|3|5|6|7|8|9])\d{8}$/,
          errorMessage: '请输入正确的手机号',
        },
      ],
    },
    fullLocation: { rules: [{ required: true, errorMessage: '请选择省市区(县)' }] },
    address: { rules: [{ required: true, errorMessage: '请输入详细地址' }] },
  }

// 表单数据
const form = ref<addressParams & { fullLocation: string }>({
  receiver: '',
  contact: '',
  fullLocation: '',
  provinceCode: '',
  cityCode: '',
  countyCode: '',
  address: '',
  isDefault: 0,
})

const onSwitchChange: UniHelper.SwitchOnChange = (e) => {
    form.value!.isDefault = e.detail.value ? 1 : 0
  },
  onLocationPickerChange: UniHelper.RegionPickerOnChange = (e) => {
    const { code, value } = e.detail,
      [provinceCode, cityCode, countyCode] = code!
    form.value.fullLocation = value.join(' ')
    Object.assign(form.value, { provinceCode, cityCode, countyCode })
  }

const onSubmit = async () => {
    try {
      await formRef.value?.validate?.()
      props.id ? editAddress() : addAddress()
    } catch {
      console.log(123)
    }
  },
  editAddress = async () => {
    const params = form.value
    const res = await editAddressApi(props.id!, params)
    if (res.code === '1') {
      uni.showToast({ title: '编辑成功', icon: 'none' })
      setTimeout(() => {
        uni.navigateBack()
      }, 500)
    }
  },
  addAddress = async () => {
    const params = form.value
    const res = await addAddressApi(params)
    if (res.code === '1') {
      uni.showToast({ title: '新增成功', icon: 'none' })
      setTimeout(() => {
        uni.navigateBack()
      }, 500)
    }
  }
</script>

<template>
  <view class="content">
    <uni-forms ref="formRef" :model="form" :rules="rules">
      <!-- 表单内容 -->
      <uni-forms-item class="form-item" name="receiver">
        <text class="label">收货人</text>
        <input class="input" placeholder="请填写收货人姓名" v-model="form.receiver" />
      </uni-forms-item>
      <uni-forms-item class="form-item" name="contact">
        <text class="label">手机号码</text>
        <input class="input" placeholder="请填写收货人手机号码" v-model="form.contact" />
      </uni-forms-item>
      <uni-forms-item class="form-item" name="fullLocation">
        <text class="label">所在地区</text>
        <picker
          class="picker"
          mode="region"
          :value="form?.fullLocation"
          @change="onLocationPickerChange"
        >
          <view v-if="form?.fullLocation">{{ form.fullLocation }}</view>
          <view v-else class="placeholder">请选择省/市/区(县)</view>
        </picker>
      </uni-forms-item>
      <uni-forms-item class="form-item" name="address">
        <text class="label">详细地址</text>
        <input class="input" placeholder="街道、楼牌号等信息" v-model="form.address" />
      </uni-forms-item>
      <uni-forms-item class="form-item" name="isDefault">
        <label class="label">设为默认地址</label>
        <switch
          class="switch"
          color="#27ba9b"
          :checked="form.isDefault == 1"
          @change="onSwitchChange"
        />
      </uni-forms-item>
    </uni-forms>
  </view>
  <!-- 提交按钮 -->
  <button class="button" @tap="onSubmit">保存并使用</button>
</template>

<style lang="scss">
page {
  background-color: #f4f4f4;
}

.content {
  margin: 20rpx 20rpx 0;
  padding: 0 20rpx;
  border-radius: 10rpx;
  background-color: #fff;

  .form-item,
  .uni-forms-item {
    display: flex;
    align-items: center;
    min-height: 96rpx;
    padding: 25rpx 10rpx 40rpx;
    background-color: #fff;
    font-size: 28rpx;
    border-bottom: 1rpx solid #ddd;
    position: relative;
    margin-bottom: 0;

    .uni-forms-item__content {
      display: flex;
    }

    .uni-forms-item__error {
      margin-left: 200rpx;
    }

    &:last-child {
      border: none;
    }

    .label {
      width: 200rpx;
      color: #333;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .switch {
      position: absolute;
      right: -20rpx;
      transform: scale(0.8);
    }

    .picker {
      flex: 1;
    }

    .placeholder {
      color: #808080;
    }
  }
}

.button {
  height: 80rpx;
  margin: 30rpx 20rpx;
  color: #fff;
  border-radius: 80rpx;
  font-size: 30rpx;
  background-color: #27ba9b;
}
</style>
